package cn.net.isir.core.shiroFilter;

import cn.net.isir.common.ResultObject;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author liuxubo
 * @filename ShiroLoginFilter.java
 * @package cn.net.isir.core.shiroFilter
 * @email lxb@isir.net.cn
 * @date 2018/11/26
 * @comment
 * @since 1.8
 */
public class ShiroLoginFilter extends FormAuthenticationFilter {

    /**
     * Determines whether the current subject should be allowed to make the current request.
     * <p/>
     * The default implementation returns <code>true</code> if the user is authenticated.  Will also return
     * <code>true</code> if the {@link #isLoginRequest} returns false and the &quot;permissive&quot; flag is set.
     *
     * @param request     request
     * @param response    response
     * @param mappedValue mappedValue
     * @return <code>true</code> if request should be allowed access
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        Subject subject = getSubject(request, response);
        return super.isAccessAllowed(request, response, mappedValue) || subject.isRemembered();
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) {
        ResultObject resultObject = new ResultObject();
        resultObject.setResult(ShiroError.NO_LOGIN_CODE);
        resultObject.setMessage(ShiroError.NO_LOGIN_MESSAGE);
        try {
            HttpServletResponse servletResponse = (HttpServletResponse) response;
//            servletResponse.setStatus(401);
            servletResponse.setCharacterEncoding("UTF-8");
            servletResponse.setContentType("application/json;charset=UTF8");
            PrintWriter printWriter = servletResponse.getWriter();
            printWriter.print(resultObject.toString());
            printWriter.flush();
            printWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}
